﻿using System;
using System.Windows;
using System.Windows.Input;
using SampleModelInterfaces;
using XtremeMvvm;

namespace SampleViewModel
{
    class SampleViewModel : ViewModelBase
    {
        private ICustomerStorage storage = ModelFactory<ICustomerStorage>.Create();

        public ICustomer CurrentCustomer
        {
            get { return (ICustomer)GetValue(CurrentCustomerProperty); }
            set { SetValue(CurrentCustomerProperty, value); }
        }

        private int quantitySaved;
        public int QuantitySaved
        {
            get { return quantitySaved; }
            set
            {
                if (quantitySaved != value)
                {
                    quantitySaved = value;
                    NotifyPropertyChanged(p => QuantitySaved);
                }
            }
        }

        public static readonly DependencyProperty CurrentCustomerProperty;

        static SampleViewModel()
        {
            CurrentCustomerProperty = DependencyProperty.Register("CurrentCustomer", typeof(ICustomer),
                typeof(SampleViewModel), new UIPropertyMetadata(ModelFactory<ICustomer>.Create()));
        }

        public void NewCustomer(object sender, RoutedEventArgs e)
        {
            MvvmHelper.SetProperty(CurrentCustomerProperty, ModelFactory<ICustomer>.Create());
        }

        public void Save_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = (CurrentCustomer.Id > 0) && (!String.IsNullOrEmpty(CurrentCustomer.Name));  //City is optional!
        }

        public void SaveCustomer(object sender, ExecutedRoutedEventArgs e)
        {
            storage.Save(MvvmHelper.GetProperty<ICustomer>(CurrentCustomerProperty));
            QuantitySaved = storage.Count;
        }
    }
}
